#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

pthread_cond_t cond_cus;
pthread_cond_t cond_chef;
pthread_mutex_t mutex;
int bowl=0;

//条件变量使用中，条件判断必须使用循环操作
//一个条件变量只有一个PCB阻塞队列，当顾客没有饭都会挂起到PCB阻塞队列中，再次唤醒唤醒的是后面的顾客导致卡死
//分开阻塞，分开等待
void *customer(void *arg){
    while(1){
        pthread_mutex_lock(&mutex);
        while(bowl==0){
            pthread_cond_wait(&cond_cus,&mutex);
        }
        bowl=0;
        printf("真好吃，再来一碗!\n");
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond_chef);//唤醒阻塞的线程
    }
    return NULL;
}
void *chef(void *arg){
    while(1){
        // !=0表示有饭，则不需要做饭，等待
        pthread_mutex_lock(&mutex);
        while(bowl!=0){
            pthread_cond_wait(&cond_chef,&mutex);
        }
        bowl=1;
        printf("23号，你的饭好了!\n");
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond_cus);//唤醒阻塞的线程
    }
    return NULL;
}
int main(){
    int ret;
    pthread_t cus_tid,chef_tid;
    pthread_cond_init(&cond_cus,NULL);
    pthread_cond_init(&cond_chef,NULL);
    pthread_mutex_init(&mutex,NULL);
    for(int i=0;i<4;i++){
        ret=pthread_create(&cus_tid,NULL,customer,NULL);
        if(ret!=0){
            printf("create thread failed!\n");
            return -1;
        }
        ret=pthread_create(&chef_tid,NULL,chef,NULL);
        if(ret!=0){
            printf("create thread failed!\n");
            return -1;
        }
    }
    pthread_join(cus_tid,NULL);
    pthread_join(chef_tid,NULL);
    pthread_cond_destroy(&cond_cus);
    pthread_cond_destroy(&cond_chef);
    pthread_mutex_destroy(&mutex);
    return 0;
}